package com.lxj.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lxj.constant.AuthConstant;
import com.lxj.mapper.SysLoginUserMapper;
import com.lxj.domain.SysLoginUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author lxj
 * @date 2021/7/30 16:20
 * @Description:
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private SysLoginUserMapper sysLoginUserMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = requestAttributes.getRequest();
        String loginType = request.getHeader(AuthConstant.LOGIN_TYPE);
        if (!StringUtils.hasText(loginType)) {
            return null;
        }
        switch (loginType) {
            case AuthConstant.USER:
                // 查询前台会员的表
            case AuthConstant.SYS_USER:
                SysLoginUser sysLoginUser = sysLoginUserMapper.selectOne(new LambdaQueryWrapper<SysLoginUser>()
                        .eq(SysLoginUser::getUsername, username));
                if (!ObjectUtils.isEmpty(sysLoginUser)) {
                    // 查询权限
                    List<String> auths = sysLoginUserMapper.selectAuthById(sysLoginUser.getUserId());
                    if (!CollectionUtils.isEmpty(auths)) {
                        sysLoginUser.setAuths(auths);
                    }
                }
                return sysLoginUser;
        }
        return null;
    }
}
